<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="上课班级" prop="courseclassId">
        <el-input v-model="queryParams.courseclassId" placeholder="请输入上课班级" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="行政班级" prop="metaclassId">
        <el-input v-model="queryParams.metaclassId" placeholder="请输入行政班级" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-input v-model="queryParams.courseclassId" placeholder="请输入上课班级" clearable @keyup.enter.native="handleQuery" /> -->
      <!-- <el-input v-model="queryParams.metaclassId" placeholder="请输入行政班级" clearable @keyup.enter.native="handleQuery" /> -->
      <!--
      <el-form-item label="上课班级" prop="courseclassId">
        <el-select v-model="form.courseclassId" filterable placeholder="请选择上课班级">
          <el-option v-for="item in courseclassList" :key="item.courseclassId" :label="item.courseclassNo"
            :value="item.courseclassId" :disabled="item.status == 1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="行政班级" prop="metaclassId">
        <el-select v-model="form.metaclassId" filterable placeholder="请选择行政班级">
          <el-option v-for="item in metaclassList" :key="item.meataclassId" :label="item.metaclassName"
            :value="item.meataclassId" :disabled="item.status == 1"></el-option>
        </el-select>
      </el-form-item> -->

      <!-- <el-select v-model="form.courseclassId" filterable placeholder="请选择上课班级">
        <el-option v-for="item in courseclassList" :key="item.courseclassId" :label="item.courseclassNo" :value="item.courseclassId"
          :disabled="item.status == 1"></el-option>
      </el-select> -->
      <!--
      <el-select v-model="form.courseId" filterable placeholder="请选择行政班级">
        <el-option v-for="item in courseList" :key="item.courseId" :label="item.courseName" :value="item.courseId"
          :disabled="item.status == 1"></el-option>
      </el-select> -->


      <!-- <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['score:courseclassMetaclass:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['score:courseclassMetaclass:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['score:courseclassMetaclass:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['score:courseclassMetaclass:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="CourseclassMetaclassList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="上课班级" align="center" prop="courseclassId" /> -->
      <el-table-column label="上课班级" align="center" prop="courseclass.courseclassNo" />
      <el-table-column label="课程" align="center" prop="courseclass.course.courseName" />
      <el-table-column label="行政班级" align="center" prop="metaclass.metaclassName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['score:courseclassMetaclass:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteId(scope.row)"
            v-hasPermi="['score:courseclassMetaclass:remove']">删除</el-button>
		  <el-button size="mini" type="text" icon="el-icon-upload2" @click="importScore"
			  >导入成绩</el-button>
		  <el-button size="mini" type="text" icon="el-icon-download" @click="exportWord"
		    >生成报告</el-button>
			<el-button size="mini" type="text"  @click="handEcharts(scope.row)"
			  >生成图表</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改行政班级上课对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="上课班级" prop="courseclassId">
          <el-select v-model="form.courseclassId" filterable placeholder="请选择上课班级">
            <el-option v-for="item in courseclassList" :key="item.courseclassId" :label="item.courseclassNo"
              :value="item.courseclassId" :disabled="item.status == 1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="行政班级" prop="metaclassId">
          <el-select v-model="form.metaclassId" filterable placeholder="请选择行政班级">
            <el-option v-for="item in metaclassList" :key="item.meataclassId" :label="item.metaclassName"
              :value="item.meataclassId" :disabled="item.status == 1"></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-select v-model="form.courseId" filterable placeholder="请选择上课班级">
          <el-option v-for="item in courseList" :key="item.courseId" :label="item.courseName" :value="item.courseId"
            :disabled="item.status == 1"></el-option>
        </el-select>

        <el-select v-model="form.courseId" filterable placeholder="请选择行政班级">
          <el-option v-for="item in courseList" :key="item.courseId" :label="item.courseName" :value="item.courseId"
            :disabled="item.status == 1"></el-option>
        </el-select> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
	<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
	  <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
	    :action="upload.url " :disabled="upload.isUploading" :data="ObjParams"
	    :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
	    <i class="el-icon-upload"></i>
	    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
	    <div class="el-upload__tip text-center" slot="tip">
	     <!-- <div class="el-upload__tip" slot="tip">
	        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
	      </div> -->
	      <span>仅允许导入xls、xlsx格式文件。</span>
	     <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
	        @click="importTemplate">下载模板</el-link>
	    </div>
	  </el-upload>
	  <div slot="footer" class="dialog-footer">
	    <el-button type="primary" @click="submitFileForm">确 定</el-button>
	    <el-button @click="upload.open = false">取 消</el-button>
	  </div>
	  </el-dialog>

	  <el-dialog  :title="echarts.title" :visible.sync="echarts.open" width="600px" >
		  <div id="main" :style="{width:'500px',height:'300px'}">
		  </div>
		  <div v-for="(item,index) in scoreList" :key="item.id">

		  <div :id=index :style="{width:'500px',height:'300px'}">
		  </div>
		  </div>
		  <!-- <div id="main2" :style="{width:'500px',height:'300px'}">
		  </div>
		  <div id="main3" :style="{width:'500px',height:'300px'}">
		  </div>
		  <div id="main4" :style="{width:'500px',height:'300px'}">
		  </div> -->
		<div slot="footer" class="dialog-footer">
		  <el-button @click="echarts.open = false">取 消</el-button>
		</div>
	  </el-dialog>

  </div>
</template>

<script>
import { listCourseclassMetaclass, getCourseclassMetaclass,upload, delCourseclassMetaclass,delCourseclassMetaclassId, addCourseclassMetaclass, updateCourseclassMetaclass } from "@/api/score/CourseclassMetaclass";
import { listCourseclass } from "@/api/score/courseclass";
import { listMetaclass } from "@/api/score/metaclass";
import { getToken } from "@/utils/auth";
import { getAverage,getScore } from "@/api/score/courseassess"

import  echarts from 'echarts';
export default {
  name: "CourseclassMetaclass",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
	  isEdit: false ,// 新增标志位
      // 总条数
      total: 0,
	  echarts:{
		  open:false,
		  title:""
	  },
	  ObjParams:{
		 courseId:this.$route.query.courseId,
	  },
	  upload: {
	    // 是否显示弹出层（用户导入）
	    open: false,
	    // 弹出层标题（用户导入）
	    title: "",
	    // 是否禁用上传
	    isUploading: false,
	    // 是否更新已经存在的用户数据
	    updateSupport: 0,
	    // 设置上传的请求头部
	    headers: { Authorization: "Bearer " + getToken() },
		// data:this.$route.query.courseId,
	    // 上传的地址
	    url: process.env.VUE_APP_BASE_API + "/score/import/",

	  },
      // 行政班级上课表格数据
      CourseclassMetaclassList: [],
	  courseassess:[],
	  courseassessName:[],
	  average:[],
	  courseId:this.$route.query.courseId,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 课程班级表格数据
      courseclassList: [],
	  scoreList:[],
      // 班级管理表格数据
      metaclassList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseclassId: this.$route.query.index,
		courseId:this.$route.query.courseId,
        metaclassId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
	this.getCourseAssess()
	this.getScore()
  },
  methods: {
    /** 查询行政班级上课列表 */
    getList() {
      this.loading = true;
      listCourseclassMetaclass(this.queryParams).then(response => {
        this.CourseclassMetaclassList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      /** 查询课程班级列表 */
      listCourseclass().then(response => {
        this.courseclassList = response.rows;
        // this.total = response.total;
        // this.loading = false;
      });
      /** 查询班级管理列表 */
      listMetaclass().then(response => {
        this.metaclassList = response.rows;
        // this.total = response.total;
        // this.loading = false;
      });
    },
	 getCourseAssess(){
		 console.log(this.courseId)
		// const courseId=this.CourseclassMetaclassList.courseclass.courseId;
		 getAverage(this.courseId).then(response=>{
			 if(response.code==200){
			this.courseassess=response.data
			for(var i=0;i<this.courseassess.length;i++){
				// this.courseassessName.push(this.courseassess[i].courseassess)
				this.courseassessName[i]=this.courseassess[i].courseassess
				this.average[i]=this.courseassess[i].average
			}
			console.log(this.courseassessName)
		}
		 })

	},
	getScore(){
		getScore(this.courseId).then(response=>{
			if(response.code==200){
				this.scoreList=response.data
				console.log(this.scoreList)
				// for(var i=0;i<this.scoreList.length;i++){

				// }
			}
		})
	},
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        courseclassId: null,
        metaclassId: null,
		preCourseclassId: null,
		preMetaclassId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.courseclassId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
	  this.isEdit = false;
      this.title = "添加行政班级上课";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
	  this.open = true;
	  this.isEdit = true;
	  this.form = row;
	  this.form.preCourseclassId = row.courseclassId
	  this.form.preMetaclassId = row.metaclassId
		console.log(this.form)
      this.title = "修改行政班级上课";
    //   const courseclassId = row.courseclassId || this.ids
    //   getCourseclassMetaclass(courseclassId).then(response => {
    //     this.form = response.data;
    //     this.open = true;
	// 	this.isEdit = true;
    //     this.title = "修改行政班级上课";
    //   });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            updateCourseclassMetaclass(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
			console.log(this.form)
            addCourseclassMetaclass(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseclassIds = row.courseclassId || this.ids;
      this.$modal.confirm('是否确认删除行政班级上课编号为"' + courseclassIds + '"的数据项？').then(function () {
        return delCourseclassMetaclass(courseclassIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

handleDeleteId(row) {
  console.log("待删除数据:", row); // 检查数据是否完整
  this.$modal.confirm('是否确认删除数据项？')
    .then(() => delCourseclassMetaclassId(row))
    .then(() => {
      this.getList();
      this.$modal.msgSuccess("删除成功");
    })
    .catch((error) => {
      console.error("删除失败详情:", error); // 打印完整错误
      this.$modal.msgError("删除失败: " + error.message);
    });
},
	//     /** 删除按钮操作 */
    // handleDeleteId(row) {
	// 	this.form = row;
    //   this.$modal.confirm('是否确认删除数据项？').then(function () {
    //     return delCourseclassMetaclassId(this.form);
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("删除成功");
    //   }).catch(() => { });
    // },
    /** 导出按钮操作 */
    handleExport() {
      this.download('score/CourseclassMetaclass/export', {
        ...this.queryParams
      }, `CourseclassMetaclass_${new Date().getTime()}.xlsx`)
    },
	importScore(){
		this.upload.title = "导入学生成绩";
		this.upload.open = true;
	},
	exportWord(){
		this.download('score/courseAssessName/export', {
		  ...this.queryParams
		}, `课程目标达成情况评价报告.docx`)
	},
	importTemplate(){
		this.download('score/downloadExcel',{},`模板.xlsx`)
	},
	// 文件上传中处理
	handleFileUploadProgress(event, file, fileList) {
	  this.upload.isUploading = true;
	  console.log(this.upload);
	},
	// 文件上传成功处理
	handleFileSuccess(response, file, fileList) {
	  this.upload.open = false;
	  this.upload.isUploading = false;
	  this.$refs.upload.clearFiles();
	  this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
	  this.getList();
	},
	// 提交上传文件
	submitFileForm() {
	  this.$refs.upload.submit();
	},
	  handEcharts(row){
		// this.getCourseAssess(row.courseclass.courseId)
		this.echarts.open=true
		this.echarts.title="各课程目标的图表"
		this.initEcharts()
	},
	 initEcharts(){

		var myChart = echarts.init(document.getElementById('main','dark'));


		// var myChart1 = echarts.init(document.getElementById('1','dark'));
		// var myChart2 = echarts.init(document.getElementById('2','dark'));
		// var myChart3 = echarts.init(document.getElementById('3','dark'));
		// 绘制图表
		myChart.setOption({
		  title: {
		    text: '各课程目标达成度整体情况'
		  },
		  tooltip: {},
		  xAxis: {
		    data: this.courseassessName
		  },
		  yAxis: {
			 type:'value',
			 name:'达成度%',
			 min:0,
			 max:100
		  },
		  series: [
		    {
		      name: '达成度%',
		      type: 'bar',
		      data: this.average
		    }
		  ]
		});
		for(var i=0;i<this.scoreList.length;i++){
			var j=i
			 j = echarts.init(document.getElementById(i,'dark'));
			j.setOption({
				title: {
				  text: '课程目标'+(i+1)+'能力分布图'
				},
				xAxis: {
				    data: [1, 11, 21, 31, 41, 51, 61]
				  },
				  yAxis: {
					type:'value',
					name:'达成度%',
					min:0,
					max:100
				  },
				  series: [
				    {
				      type: 'scatter',
					  markLine:{
						  data:[{name:'平均值'+this.scoreList[i].average,yAxis:this.scoreList[i].average},{name:'预期值60',yAxis:this.scoreList[i].expected}]
					  },
				      data: this.scoreList[i].scores
				    }
				  ]
			});
		}
		// myChart0.setOption({
		// 	title: {
		// 	  text: '课程目标1能力分布图'
		// 	},
		// 	xAxis: {
		// 	    data: [1, 11, 21, 31, 41, 51, 61]
		// 	  },
		// 	  yAxis: {
		// 		type:'value',
		// 		name:'达成度%',
		// 		min:0,
		// 		max:100
		// 	  },
		// 	  series: [
		// 	    {
		// 	      type: 'scatter',
		// 		  markLine:{
		// 			  data:[{name:'平均值'+this.scoreList[0].average,yAxis:this.scoreList[0].average},{name:'预期值60',yAxis:this.scoreList[0].expected}]
		// 		  },
		// 	      data: this.scoreList[0].scores
		// 	    }
		// 	  ]
		// });
		// myChart1.setOption({
		// 	title: {
		// 	  text: '课程目标2能力分布图'
		// 	},
		// 	xAxis: {
		// 	    data: [1, 11, 21, 31, 41, 51, 61]
		// 	  },
		// 	  yAxis: {
		// 		type:'value',
		// 		name:'达成度%',
		// 		min:0,
		// 		max:100
		// 	  },
		// 	  series: [
		// 	    {
		// 	      type: 'scatter',
		// 		  markLine:{
		// 			  data:[{name:'平均值'+this.scoreList[1].average,yAxis:this.scoreList[1].average},{name:'预期值60',yAxis:this.scoreList[1].expected}]
		// 		  },
		// 	      data: this.scoreList[1].scores
		// 	    }
		// 	  ]
		// });
		// myChart2.setOption({
		// 	title: {
		// 	  text: '课程目标3能力分布图'
		// 	},
		// 	xAxis: {
		// 	    data: [1, 11, 21, 31, 41, 51, 61]
		// 	  },
		// 	  yAxis: {
		// 		type:'value',
		// 		name:'达成度%',
		// 		min:0,
		// 		max:100
		// 	  },
		// 	  series: [
		// 	    {
		// 	      type: 'scatter',
		// 		  markLine:{
		// 			  data:[{name:'平均值'+this.scoreList[2].average,yAxis:this.scoreList[2].average},{name:'预期值60',yAxis:this.scoreList[2].expected}]
		// 		  },
		// 	      data: this.scoreList[2].scores
		// 	    }
		// 	  ]
		// });
		// myChart3.setOption({
		// 	title: {
		// 	  text: '课程目标4能力分布图'
		// 	},
		// 	xAxis: {
		// 	    data: [1, 11, 21, 31, 41, 51, 61]
		// 	  },
		// 	  yAxis: {
		// 		type:'value',
		// 		name:'达成度%',
		// 		min:0,
		// 		max:100
		// 	  },
		// 	  series: [
		// 	    {
		// 	      type: 'scatter',
		// 		  markLine:{
		// 			  data:[{name:'平均值'+this.scoreList[3].average,yAxis:this.scoreList[3].average},{name:'预期值60',yAxis:this.scoreList[3].expected}]
		// 		  },
		// 	      data: this.scoreList[3].scores
		// 	    }
		// 	  ]
		// });
	}
  },
  mounted() {

  },
  updated() {
  	this.initEcharts()
  }
};
</script>
